"""7.3 sqlalchemy  ORM-查询数据"""
#连接数据库
from sqlalchemy import create_engine, Column, Integer, String, Text, Float, DateTime
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 创建数据库连接
engine = create_engine('mysql+mysqlconnector://root:123456@127.0.0.1:3306/django-web')
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
print("打印出session:",session)
# 创建基类
Base = declarative_base()
print("打印出Base:",Base)
# 定义模型
class Article(Base):
    #映射表名
    __tablename__ = 'blog_article'
    '''标题 title,内容 content,作者 author,价格 price,发布日期 pub_date,状态 status'''
    id = Column(Integer, primary_key=True)
    title = Column(String(200))
    content = Column(Text)
    author = Column(String(100))
    price = Column(Float)
    pub_date = Column(DateTime)
    status = Column(Integer)
    def __repr__(self):
        return f"<Article(title='{self.title}', author='{self.author}')>"
    '''标题 title,内容 content,作者 author,价格 price,发布日期 pub_date,状态 status'''
    def __str__(self):
        return f"title:{self.title}, content:{self.content}, author:{self.author}, price:{self.price}, pub_date:{self.pub_date}, status:{self.status}"

#数据库的查询
#查询所有文章
articles = session.query(Article).all()
print("查询所有文章:",articles)
for article in articles:
    print(article)

#带条件的查询
#查询id为1的文章
article = session.query(Article).filter_by(id=17).first()
print("查询id为1的文章:",article)
#查询价格大于100的文章
articles = session.query(Article).filter(Article.price >= 100).all()
print("查询价格大于100的文章:",articles)
for article in articles:
    print(article)